package com.lp.biz.identity.service.impl;
import java.time.LocalDateTime;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lp.biz.ComponentService;
import com.lp.biz.identity.mapper.*;
import com.lp.biz.identity.model.entity.*;
import com.lp.biz.identity.service.BizIdentityService;
import com.lp.biz.member.service.MemberService;
import com.lp.common.entity.CommonAll;
import com.lp.common.utils.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.lp.common.constant.CommonConstant.NEGATE;

/**
 * @program: backend
 * @description: BizIdentity 服务实现类
 * @author Ke.Song
 * @since 2024-05-14 20:43:28
 */
@Slf4j
@Service
public class BizIdentityServiceImpl extends ServiceImpl<BizIdentityMapper, BizIdentity> implements BizIdentityService {

    @Autowired
    private MemberService memberService;

    @Autowired
    private AdvisorMapper advisorMapper;

    @Autowired
    private ComponentService componentService;

    @Autowired
    private BizIdentityMemberRelMapper identityMemberRelMapper;

    @Override
    public CommonResult getIdentityDown() {
        List<CommonAll> result = new ArrayList<>(6);
        for (BizIdentity identity : list()) {
            result.add(new CommonAll(identity.getId(), identity.getName()));
        }
        return CommonResult.success(result);
    }

    @Override
    public CommonResult getAdvisorDown() {
        List<CommonAll> result = new ArrayList<>(6);
        for (Advisor advisor : advisorMapper.selectList(new QueryWrapper<>())) {
            result.add(new CommonAll(advisor.getId(), advisor.getName()));
        }
        return CommonResult.success(result);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addIdentity(Integer memberId, Integer identityId) {
        BizIdentity identity = getById(identityId);
        BizIdentityMemberRel rel = identityMemberRelMapper.selectOne(new QueryWrapper<BizIdentityMemberRel>().lambda()
                .eq(BizIdentityMemberRel::getMemberId, memberId)
                .eq(BizIdentityMemberRel::getBizIdentityId, identityId));
        if (rel == null) {
            rel = new BizIdentityMemberRel();
            rel.setMemberId(memberId);
            rel.setBizIdentityId(identity.getId());
            rel.setIsDefault(NEGATE);
            rel.setIsEffective(NEGATE);
            rel.setCreateAt(LocalDateTime.now());
            rel.setSource(2);
            identityMemberRelMapper.insert(rel);
            componentService.setDefault(rel, identity);
        }
        memberService.updateRate(memberId, identity.getRate());
    }
}
